package example.servlet;

import java.io.IOException;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import example.model.App;
import example.model.User;
import org.owasp.jxt.UrlBuilder;

public class NewUserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException
    {
        showForm(req, res);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException
    {
        App app = (App)getServletContext().getAttribute("app");

        String name = req.getParameter("name");
        String password = req.getParameter("password");
        String confirmPassword = req.getParameter("confirm-password");

        if (null == name || "".equals(name) ||
            null == password || "".equals(password) ||
            null == confirmPassword || "".equals(confirmPassword))
        {
            showMessage(req, res, "Missing required parameter(s).");
        } else if (!password.equals(confirmPassword)) {
            showMessage(req, res, "Password and confirm password do not match.");
        } else if (app.getUser(name) != null) {
            showMessage(req, res, "A user with that name already exists.  Please choose another name.");
        } else {
            User user = app.createUser(name, password);
            req.getSession().setAttribute("user", user);
            res.sendRedirect(
                res.encodeRedirectURL("feed.jxt"));
        }
    }

    void showMessage(HttpServletRequest req,
                     HttpServletResponse res,
                     String message)
        throws ServletException, IOException
    {
        req.setAttribute("message", message);
        showForm(req, res);
    }

    void showForm(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException
    {
        getServletContext()
            .getRequestDispatcher("/WEB-INF/jxt/new-user.jxt")
            .include(req, res);
    }
}
